﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using JT.Data;
using JT.Domain;
using Microsoft.AspNetCore.Authentication;

namespace JT.WEB.Service
{

    public class UserCenterService : IUserCenter
    {
        private readonly ContextBase _baseContext;
        public UserCenterService(ContextBase baseContext)
        {
            _baseContext = baseContext;
        }

        public async Task<int> AddMessage(Message message)
        {
            message.Read = false;
            await _baseContext.Messages.AddAsync(message);
            int x = await _baseContext.SaveChangesAsync();
            return x;
        }

        public IEnumerable<Message> GetMessages(Expression<Func<Message, bool>> where)
        {
            List<Message> vm = _baseContext.Messages.Where(where).ToList();
            return vm;
        }
        public IEnumerable<Message> GetUnreadMS()
        {
            List<Message> vm = _baseContext.Messages.Where(c => !c.Read).ToList(); //获取未读消息
            return vm;
        }
        //public int GetUnReadMSCount(Expression<Func<Message, bool>> where)
        //{
        //    var x = _uCContext.Messages.Where(c => !c.Read).Count(where);
        //    return x;
        //}
        /// <summary>
        /// 获取未读消息数量
        /// </summary>
        /// <returns>返回未读消息数量</returns>
        public int GetUnReadMSCount()
        {
            int x = GetMessages(c => c.Read == false).Count();
            return x;
        }

        public async Task<int> ReadAsync(EMSLevel eMSLevel)
        {
            IEnumerable<Message> UnreadMS = this.GetMessages(m => m.MSLevel == eMSLevel && m.Read == false);
            if (UnreadMS.Count() > 0)
            {
                foreach (Message i in UnreadMS)
                {
                    i.Read = true;
                }
                int a = await _baseContext.SaveChangesAsync();
                return a;
            }
            return 0;

        }
    }
}
